import json
import time
import webapp2

from webapp2_extras.i18n import gettext as _

from apnetmodels.basicmodels import immeuble, period_concept
from google.appengine.api import users

from wtforms.ext.appengine.db import model_form

from common import functions

from BaseHandler import BaseHandler

class PeriodConcept(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(PeriodConcept, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'date_start': _('Start date'), 'date_finish': _('Finish date'), 'closed': _('Budget closed'), 
                       'close_accounting': _('Accounting closed'), 'immeuble': _('Tenement')
                       }
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        template_values = {
                           'title': _('Period Concept. %s' % imm.name),
                           'header': _('ATENET. Period Concept. %s' % imm.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'syndic',
                           'leftmenu': 'period_concept',
                           'fields': self.fields
        }

        template = self.jinja2.get_template('templates/period_concept_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        query = imm.period_concept_set.order('-date_start').order('-date_finish').run()
        pc = []
        for e in query:
            pc.append([functions.datetimeformat(e.date_start), functions.datetimeformat(e.date_finish), functions.TrueFalseToYesNoFormat(e.closed), str(e.key().id())])
        ret = {}
        ret['aaData'] = pc
        self.response.out.write(json.dumps(ret))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        ok_message = ''
        PeriodConceptForm = model_form(period_concept, exclude=['immeuble', 'lastchange_by', 'lastchange_date', 'budget', 'tantiem_price'])
        
        if self.request.method == 'GET':
            form = PeriodConceptForm()
            
        if self.request.method == 'POST':
            form = PeriodConceptForm(self.request.POST)
            if form.validate():
                pc_obj = period_concept(
                                        date_start = form['date_start'].data,
                                        date_finish = form['date_finish'].data,
                                        closed = form['closed'].data,
                                        immeuble= imm,
                                        lastchange_by=self.au
                                        )
                pc_obj.put()
                while not pc_obj.is_saved():
                    time.sleep(2)
                
                ok_message = _('Period concept was added.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        pc_id = kwargs.get('pc_id', -1)
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        pc_obj = period_concept.get_by_id(int(pc_id))
        
        ok_message = ''
        PeriodConceptForm = model_form(period_concept, exclude=['immeuble', 'lastchange_by', 'lastchange_date', 'budget', 'tantiem_price'])
        
        if self.request.method == 'GET':
            form = PeriodConceptForm(obj=pc_obj)
            
        if self.request.method == 'POST':
            form = PeriodConceptForm(self.request.POST)
            if form.validate():
                form.populate_obj(pc_obj)
                pc_obj.put()
                
                ok_message = _('Period concept was updated.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
